import 'dart:developer';

import 'package:flutter_admin/models/odoo/sale_bid_project.dart';
import 'package:flutter_admin/pages/common/cry/common/application_context.dart';
import 'package:flutter_admin/pages/common/cry/cry.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/cry_dialog.dart';
import 'package:flutter_admin/pages/common/cry/model/application.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/dms_file_odoo_api.dart';
import 'package:flutter_admin/constants/constant.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/dms_file.dart';
import 'package:flutter_admin/models/odoo/udt_tb_docmentstock.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:fluttertoast/fluttertoast.dart';

import 'dms_file_upload.dart';
import 'select_docmentstock_list.dart';

class DmsFileList extends StatefulWidget {
  UdtTbDocmentstock? udtTbDocmentstock;
  SaleBidProject? saleBidProject;
  String? documentno;
  String? uploadFileType;
  DmsFileList(
      {required this.udtTbDocmentstock,
      required this.saleBidProject,
      this.documentno,
      this.uploadFileType,
      Key? key})
      : super(key: key);

  @override
  _DmsFileListState createState() => _DmsFileListState();
}

class _DmsFileListState extends State<DmsFileList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  // final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page = PageModel(orders: [
    OrderItemModel(column: 'create_date', asc: false),
  ]);
  DmsFile dmsFile = DmsFile();
  List<DmsFile> selectedList = [];
  @override
  void initState() {
    /**
     * 这块的代码，不具有扩展性，需要将参数进行替换
     * date: 2022-5-16
     * author: 陈德基
     */
    if (widget.udtTbDocmentstock != null) {
      dmsFile.documentno = widget.udtTbDocmentstock!.documentno;
    } else if (widget.saleBidProject != null) {
      dmsFile.documentno = widget.saleBidProject!.projectcode;
    } else if (widget.documentno != null) {
      dmsFile.documentno = widget.documentno;
    }
    super.initState();
    _loadSelectVO();

    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
    });
  }

  _loadSelectVO() async {
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        // DataColumn(
        //   label: Text('文档编号'),
        //   onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        // ),
        DataColumn(
          label: Text('附件名称'),
          // onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('备注'),
          // onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('创建人'),
          // onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('创建日期'),
          // onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
      ],
      getCells: (m) {
        DmsFile dmsFile = DmsFile.fromMap(m);
        return [
          // DataCell(Text(dmsFile.documentno ?? '--')),
          DataCell(Text(dmsFile.name ?? '--')),
          DataCell(Text(dmsFile.remark ?? '--')),
          DataCell(Text(dmsFile.createName ?? '--')),
          DataCell(Text(Utils.timeUTC(dmsFile.createDate) ?? '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        // CryButtons.query(context, () => _query()),
        CryButton(
          label: "上传",
          onPressed: () {
            _upload();
          },
          iconData: Icons.upload_rounded,
        ),

        CryButtons.download(
          context,
          selectedList.length != 1 ? null : () => _download(selectedList[0].id),
        ),
        // CryButtons.reset(context, () => _reset()),
        // CryButtons.add(context, () => _edit(null)),
        // CryButtons.edit(context,
        //     selectedList.length != 1 ? null : () => _edit(selectedList[0])),
        CryButtons.delete(context,
            selectedList.length < 1 ? null : () => _delete(selectedList)),
        widget.udtTbDocmentstock != null
            ? CryButton(
                label: "文档转移",
                iconData: Icons.view_headline,
                onPressed: selectedList.length >= 1
                    ? () => _fileTransfer(selectedList)
                    : null,
              )
            : Text(""),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      appBar: AppBar(
        leading: Builder(
          builder: (BuildContext context) {
            final ScaffoldState? scaffold = Scaffold.maybeOf(context);
            final ModalRoute<Object?>? parentRoute = ModalRoute.of(context);
            final bool canPop = parentRoute?.canPop ?? false;

            if (canPop) {
              return BackButton();
            } else {
              return SizedBox.shrink();
            }
          },
        ),
        title: Text('电子文档管理'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          // isDisplayDesktop(context)?form:Container(),
          isDisplayDesktop(context) ? buttonBar : Container(),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _query() {
    // formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi = await DmsFileOdooApi.page(
        data: {"page": page, "domainList": dmsFile.toDomainList()});
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  ///
  ///删除附件，需要判断权限
  ///@Author: chendeji
  ///@Date: 2022-05-19 11:38:30
  ///
  _delete(List<DmsFile> selectedList) async {
    var userID = StoreUtil.getCurrentUserInfo().userId;
    cryConfirm(context, S.of(context).confirmDelete, (context) async {
      List ids = selectedList.map((v) {
        return int.parse(v.id!);
      }).toList();
      /**
       * 
       * 添加一个判断，判断删除的附件中是否有别人上传的附件，如果有则不能进行删除 
       * 
       * @Author: chendeji
       * @Date: 2022-05-19 11:30:37
      */
      bool notOwner =
          ids.firstWhere((element) => element != int.parse(userID!));
      if (notOwner) {
        Fluttertoast.showToast(msg: '无权限删除其他人上传附件');
        return;
      }
      var result = await DmsFileOdooApi.removeByIds(ids);
      if (result.success!) {
        _query();
        CryUtils.message(S.of(Cry.context).success);
      }
    });
  }

  _sort(column, {ascending}) {
    page.orders[0].column = column;
    page.orders[0].asc = ascending ?? !page.orders[0].asc!;
    _query();
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<DmsFile>((e) => DmsFile.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _upload() async {
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: DmsFileUpload(
          documentno: dmsFile.documentno,
          type: widget.uploadFileType,
        ),
      ),
    ).then((v) {
      if (v != null) {
        _query();
      }
    });
  }

  _download(id) {
    //todo/web/content?model=dms.file&id=87&field=content&download=true
    Application application = ApplicationContext.instance.application;
    var odooBaseUrl = application.odooBaseUrl!;
    var data = StoreUtil.read(Constant.CLIENT);
    http: //47.95.117.205:8099/quninmadexiazaiwenjian/admin&admin&135
    // Utils.launchURL("${odooBaseUrl}web/content?model=dms.file&id=$id&field=content&download=true");
    Utils.launchURL(
        "${odooBaseUrl}web/quninmadexiazaiwenjian/${data['login']}&${data['password']}&$id");
  }

  _fileTransfer(List<DmsFile> selectedList) {
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: SelectDocmentstockList(
          dmsfiles: selectedList,
        ),
      ),
    ).then((v) {
      if (v != null) {
        _query();
        // setState(() {});
      }
    });
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          // _search();
        } else if (v == OperationType.add) {
          //todo 这里偷个懒 利用添加和修改枚举代替上传下载
          //上传
          _upload();
        } else if (v == OperationType.edit) {
          //下载
          _download(selectedList[0].id);
          // downloadFile(selectedList[0].id);
        } else if (v == OperationType.delete) {
          cryConfirm(context, S.of(context).confirmDelete, (context) async {
            _delete(selectedList);
          });
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        // PopupMenuItem<OperationType>(
        //   value: OperationType.query,
        //   child: ListTile(
        //     leading: const Icon(Icons.search),
        //     title: Text('查询'),
        //   ),
        // ),
        PopupMenuItem<OperationType>(
          value: OperationType.add,
          child: ListTile(
            leading: const Icon(Icons.upload_rounded),
            title: Text('上传'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.edit,
          enabled: selectedList.length == 1,
          child: ListTile(
            enabled: selectedList.length == 1,
            leading: const Icon(Icons.download_rounded),
            title: Text('下载'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.delete,
          enabled: selectedList.length != 0,
          child: ListTile(
            leading: const Icon(Icons.delete), //Icons.delete
            enabled: selectedList.length != 0,
            title: Text('删除'),
          ),
        ),
      ],
    );
  }
}
